package office

import (
	"common/api"
	"common/utils"
	"common/web/file"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"os"
	"path/filepath"
	"strings"
)

func DocxAnalyzeViews(ctx *gin.Context) {
	fileId := ctx.Query("fileId")

	//接收参数问题
	if len(fileId) == 0 {
		utils.ResponseFail(ctx, "not fileId receive")
		return
	}

	//数据库不存在问题
	fileInfo := file.GetFileInfoById(fileId)
	if len(fileInfo.Md5) == 0 {
		utils.ResponseFail(ctx, "fileId not exists")
		return
	}

	//判断文件类型问题
	if !strings.Contains(strings.ToLower(fileInfo.Ext), "docx") {
		utils.ResponseFail(ctx, "fileId type error")
		return
	}

	filePath := utils.GetFilePath(fileInfo.FName)
	distPath := utils.GetFilePath(fileInfo.FName)

	//删除文件夹
	defer func(name string) {
		err := os.Remove(name)
		if err != nil {
		}
	}(filepath.Dir(filePath))

	//删除文件
	defer func(name string) {
		err := os.Remove(name)
		if err != nil {
		}
	}(filePath)

	defer func(name string) {
		err := os.Remove(name)
		if err != nil {
		}
	}(filepath.Dir(distPath))

	defer func(name string) {
		err := os.Remove(name)
		if err != nil {
		}
	}(distPath)

	err := api.ObsDownload(fileInfo.ObsFileId, filePath)

	if err != nil {
		utils.ResponseFail(ctx, "fileId download failed")
		return
	}

	//文件转换
	tagContainer, err1 := utils.WordSDKResolve(filePath, distPath)
	if err1 != nil {
		utils.ResponseFail(ctx, err1.Error())
		return
	}

	//上传obs和数据库
	distFileInfo := file.GetFileInfo(distPath)
	utils.ResponseOK(ctx, gin.H{"fileId": distFileInfo.FileId, "data": tagContainer})
}

func DocxFillViews(ctx *gin.Context) {
	dataByte, _ := ctx.GetRawData()
	var m map[string]interface{}
	_ = json.Unmarshal(dataByte, &m)

	fileId := m["fileId"].(string)
	data := m["data"].(map[string]interface{})
	//接收参数问题
	if len(fileId) == 0 {
		utils.ResponseFail(ctx, "not fileId receive")
		return
	}

	//数据库不存在问题
	fileInfo := file.GetFileInfoById(fileId)
	if len(fileInfo.Md5) == 0 {
		utils.ResponseFail(ctx, "fileId not exists")
		return
	}

	//判断文件类型问题
	if !strings.Contains(strings.ToLower(fileInfo.Ext), "docx") {
		utils.ResponseFail(ctx, "fileId type error")
		return
	}

	filePath := utils.GetFilePath(fileInfo.FName)
	distPath := utils.GetFilePath(fileInfo.FName)

	//删除文件夹
	defer func(name string) {
		err := os.Remove(name)
		if err != nil {
		}
	}(filepath.Dir(filePath))

	//删除文件
	defer func(name string) {
		err := os.Remove(name)
		if err != nil {
		}
	}(filePath)

	defer func(name string) {
		err := os.Remove(name)
		if err != nil {
		}
	}(filepath.Dir(distPath))

	defer func(name string) {
		err := os.Remove(name)
		if err != nil {
		}
	}(distPath)

	err := api.ObsDownload(fileInfo.ObsFileId, filePath)

	if err != nil {
		utils.ResponseFail(ctx, "fileId download failed")
		return
	}

	//文件转换
	err1 := utils.WordSDKFill(filePath, distPath, data)
	if err1 != nil {
		utils.ResponseFail(ctx, err1.Error())
		return
	}

	//上传obs和数据库
	distFileInfo := file.GetFileInfo(distPath)
	utils.ResponseOK(ctx, gin.H{"fileId": distFileInfo.FileId})
}
